// 购物车模块 - 演示Vuex模块化管理
export default {
    // 开启命名空间，避免模块间的命名冲突
    namespaced: true,
    
    state: {
        // 购物车商品列表
        items: [],
        // 商品库存信息
        products: [
            { id: 1, name: 'Vue教程书籍', price: 99, inventory: 10 },
            { id: 2, name: 'React实战指南', price: 129, inventory: 5 },
            { id: 3, name: 'JavaScript高级程序设计', price: 79, inventory: 8 },
            { id: 4, name: 'Node.js开发实战', price: 89, inventory: 12 }
        ],
        // 结账状态
        checkoutStatus: null
    },
    
    mutations: {
        // 添加商品到购物车
        ADD_TO_CART(state, { id, quantity = 1 }) {
            const existingItem = state.items.find(item => item.id === id)
            if (existingItem) {
                existingItem.quantity += quantity
            } else {
                state.items.push({ id, quantity })
            }
        },
        
        // 从购物车移除商品
        REMOVE_FROM_CART(state, id) {
            const index = state.items.findIndex(item => item.id === id)
            if (index > -1) {
                state.items.splice(index, 1)
            }
        },
        
        // 更新商品数量
        UPDATE_QUANTITY(state, { id, quantity }) {
            const item = state.items.find(item => item.id === id)
            if (item) {
                if (quantity <= 0) {
                    // 数量为0时移除商品
                    const index = state.items.findIndex(item => item.id === id)
                    state.items.splice(index, 1)
                } else {
                    item.quantity = quantity
                }
            }
        },
        
        // 清空购物车
        CLEAR_CART(state) {
            state.items = []
        },
        
        // 更新库存
        UPDATE_INVENTORY(state, { id, quantity }) {
            const product = state.products.find(p => p.id === id)
            if (product) {
                product.inventory -= quantity
            }
        },
        
        // 设置结账状态
        SET_CHECKOUT_STATUS(state, status) {
            state.checkoutStatus = status
        }
    },
    
    actions: {
        // 添加商品到购物车（检查库存）
        addToCart({ state, commit, getters }, { id, quantity = 1 }) {
            const product = state.products.find(p => p.id === id)
            if (!product) {
                return { success: false, message: '商品不存在' }
            }
            
            if (product.inventory < quantity) {
                return { success: false, message: '库存不足' }
            }
            
            // 检查购物车中已有数量
            const cartItem = state.items.find(item => item.id === id)
            const currentQuantity = cartItem ? cartItem.quantity : 0
            
            if (product.inventory < currentQuantity + quantity) {
                return { success: false, message: '超出库存限制' }
            }
            
            commit('ADD_TO_CART', { id, quantity })
            return { success: true, message: '已添加到购物车' }
        },
        
        // 更新购物车商品数量
        updateCartItemQuantity({ commit, state }, { id, quantity }) {
            const product = state.products.find(p => p.id === id)
            if (product && quantity > product.inventory) {
                return { success: false, message: '超出库存限制' }
            }
            
            commit('UPDATE_QUANTITY', { id, quantity })
            return { success: true }
        },
        
        // 移除购物车商品
        removeFromCart({ commit }, id) {
            commit('REMOVE_FROM_CART', id)
        },
        
        // 结账流程
        async checkout({ state, commit }) {
            commit('SET_CHECKOUT_STATUS', 'pending')
            
            try {
                // 模拟API请求
                await new Promise(resolve => setTimeout(resolve, 2000))
                
                // 检查库存
                for (const item of state.items) {
                    const product = state.products.find(p => p.id === item.id)
                    if (!product || product.inventory < item.quantity) {
                        throw new Error(`商品 ${product ? product.name : 'Unknown'} 库存不足`)
                    }
                }
                
                // 更新库存
                state.items.forEach(item => {
                    commit('UPDATE_INVENTORY', { id: item.id, quantity: item.quantity })
                })
                
                // 清空购物车
                commit('CLEAR_CART')
                commit('SET_CHECKOUT_STATUS', 'success')
                
                return { success: true, message: '结账成功！' }
                
            } catch (error) {
                commit('SET_CHECKOUT_STATUS', 'failed')
                return { success: false, message: error.message }
            }
        }
    },
    
    getters: {
        // 购物车商品详情列表
        cartItems: (state) => {
            return state.items.map(item => {
                const product = state.products.find(p => p.id === item.id)
                return {
                    ...product,
                    quantity: item.quantity,
                    totalPrice: product.price * item.quantity
                }
            })
        },
        
        // 购物车总价
        cartTotal: (state, getters) => {
            return getters.cartItems.reduce((total, item) => {
                return total + item.totalPrice
            }, 0)
        },
        
        // 购物车商品总数量
        cartItemCount: (state) => {
            return state.items.reduce((count, item) => count + item.quantity, 0)
        },
        
        // 可购买的商品列表（有库存的商品）
        availableProducts: (state) => {
            return state.products.filter(product => product.inventory > 0)
        },
        
        // 获取指定商品的库存信息
        getProductById: (state) => (id) => {
            return state.products.find(product => product.id === id)
        },
        
        // 检查购物车是否为空
        isCartEmpty: (state) => {
            return state.items.length === 0
        }
    }
}